#include "../../include/system/Utils.h"
#include <algorithm>

namespace MiniBanking
{
    // Helper function to get the current local time structure
    static std::tm getCurrentLocalTime()
    {
        auto now = std::chrono::system_clock::now();
        auto in_time_t = std::chrono::system_clock::to_time_t(now);
        // Use localtime_s on Windows, localtime_r on POSIX for thread safety
        std::tm timeinfo = *std::localtime(&in_time_t);
        return timeinfo;
    }

    std::string Utils::getCurrentDateString()
    {
        std::tm timeinfo = getCurrentLocalTime();
        std::stringstream ss;
        ss << std::put_time(&timeinfo, "%Y-%m-%d");
        return ss.str();
    }

    std::string Utils::getCurrentDateTimeString()
    {
        std::tm timeinfo = getCurrentLocalTime();
        std::stringstream ss;
        ss << std::put_time(&timeinfo, "%Y-%m-%d %H:%M:%S");
        return ss.str();
    }

    std::string Utils::sanitizeFilenamePart(const std::string &input)
    {
        std::string sanitized = input;
        // Replace spaces with underscores
        std::replace(sanitized.begin(), sanitized.end(), ' ', '_');

        return sanitized;
    }

    std::string Utils::formatTimestamp(const std::chrono::system_clock::time_point &timePoint)
    {
        auto time_t_point = std::chrono::system_clock::to_time_t(timePoint);
        std::tm timeinfo = *std::localtime(&time_t_point);
        std::stringstream ss;
        ss << std::put_time(&timeinfo, "%Y-%m-%d %H:%M:%S");
        return ss.str();
    }

}
